# -*- encoding=utf-8 -*-
from flask import Flask, render_template, session, redirect, url_for
from flask import request

from utils.wx_mssql_push import WX_MSSQL_Push
from utils.wxapi import WxClient
from utils.dbm import DBManager
from utils.configReader import myconfigReader
from app import app
from functools import wraps
from datetime import timedelta
from urllib import parse
import logging
import logging.config

import time
import threading

def need_login(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if 'currentUser' in session and session['currentUser'] is not None:
            return func(*args, **kwargs)
        else:
            # return login_select()
            aim_url = url_for('login_select')
            return redirect("%s?aim_url=%s" %(aim_url, request.url))
    return wrapper


def is_admin(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if 'currentUser' in session:
            if session['currentUser'] in myconfigReader.admin_mp:
                return func(*args, **kwargs)
        return render_template("no_permission.html")
    return wrapper


@app.route('/')
def index():
    return render_template("service.html")


@app.route('/login', methods=['POST', 'GET'])
def login():
    if 'username' in request.form and 'password' in request.form:
        username = request.form['username']
        password = request.form['password']

        #先去admin列表里面查询是否为管理员
        if check_login_with_admin_mp(username, password):
            session['currentUser'] = username
            session['is_admin'] = 'True'
            if 'aim_url' in request.args:
                return redirect(request.args['aim_url'])
            else:
                return feedback_list()

        #再去数据库中对照
        mydb = DBManager()
        ret = mydb.checkUser(username, password)
        if ret == True:
            session['currentUser'] = username
            if 'aim_url' in request.args:
                return redirect(request.args['aim_url'])
            else:
                return feedback_list()
        errmsg = "用户名或密码错误"
        mydb.close()
        return render_template("login.html", errmsg=errmsg)

    if 'aim_url' in request.args:
        return render_template("login.html", aim_url=request.args['aim_url'])
    else:
        return render_template("login.html")


def check_login_with_admin_mp(username, password):
    if username in myconfigReader.admin_mp:
        real_password = myconfigReader.admin_mp[username]
        if password == real_password:
            return True
    return False

@app.route('/logout')
def logout():
    session.pop('currentUser',None)
    if 'is_admin' in session:
        session.pop('is_admin',None)
    return login_select()


@app.route('/wechat_login')
def wechat_login():
    wx_client = WxClient()
    wechat_id = wx_client.get_wechat_id_by_code(request.args['code'])
    if wechat_id is None:
        return render_template("msg.html",msg="该微信账号没有权限")
    mydb = DBManager()
    print(wechat_id)
    username = mydb.get_username_by_wechat_id(wechat_id)
    mydb.close()
    if username is None:
        return render_template("msg.html", msg="该微信账号没有权限")
    session['currentUser'] = username
    if username_in_admin(username):
        session['is_admin'] = 'True'
    if 'aim_url' in request.args:
        return redirect(request.args['aim_url'])
    else:
        return feedback_list()


def username_in_admin(username):
    if username in myconfigReader.admin_mp:
        return True
    return False

@app.route('/login_select')
def login_select():
    redirect_url = 'http://%s/wechat_login' %myconfigReader.domain
    if 'aim_url' in request.args:
        return render_template("login_select.html", corpid=myconfigReader.corpid, re_url=redirect_url, aim_url=request.args['aim_url'])
    else:
        return render_template("login_select.html",corpid=myconfigReader.corpid,re_url=redirect_url)


@app.route('/add_user', methods=['POST', 'GET'])
@is_admin
def add_user():
    if 'username' in request.form:
        username = request.form['username']
        password = request.form['password']
        password_repeat = request.form['password_repeat']
        name = request.form['name']
        wechat_id = request.form['wechat_id']
        mydb = DBManager()
        msg = mydb.add_user(username,password,password_repeat,name,wechat_id)
        mydb.close()
        if msg == 'success':
            return render_template("msg.html", msg="添加用户成功")
        else:
            return render_template("add_user.html", errmsg=msg)
    return render_template("add_user.html")


@app.route('/sub_question', methods=['POST', 'GET'])
def sub_question():
    if 'serviceType' not in request.form:
        return render_template("service.html",errmsg="请选择服务类型",vs=request.form)
    mydb = DBManager()
    name = request.form['name']
    phone = request.form['phone']
    address = request.form['address']
    booktime = request.form['booktime']
    serviceType = get_real_service_type(request.form['serviceType'])
    content = request.form['content']
    title = request.form['title']

    if trim(name) == '':
        return render_template("service.html", errmsg="请填写您的姓名", vs=request.form)

    if trim(title) == '':
        return render_template("service.html", errmsg="请填写简要说明", vs=request.form)

    if trim(phone) == '':
        return render_template("service.html", errmsg="请填写您的联系方式", vs=request.form)

    #插入数据库
    id = mydb.insertToFeedback(name=name,phone=phone,address=address,title=title,\
                          booktime=booktime,serviceType=serviceType,content=content)
    mydb.close()
    feedback_url = "http://%s/feedback_item/%s" %(myconfigReader.domain, id)
    msg = "收到一条客户反馈\n姓名：%s\n手机号：%s\n链接：%s" %(name, phone, feedback_url)
    wx_client = WxClient()
    status = wx_client.addNewService(toUser=myconfigReader.feedback_add_receiver,toParty=None,content=msg)
    if status == True:
        return render_template("sub_success.html")
    return render_template("sub_error.html")

def trim(s):
    s = s.strip(' ')
    s = s.strip('\t')
    s = s.strip('\n')
    s = s.strip('\r')
    return s

def get_real_service_type(serviceType):
    if serviceType == 'wx':
        return '维修'
    elif serviceType == 'by':
        return '保养'
    elif serviceType == 'cz':
        return '拆装'
    return None

@app.route('/feedback_list')
@need_login
def feedback_list():
    mydb = DBManager()
    feedbacks = mydb.selectAllFeedbacks()
    mydb.close()
    return render_template("feedback_list.html",feedbacks=feedbacks)

@app.route('/feedback_list/<status>')
@need_login
def feedback_list_by_status(status):
    mydb = DBManager()
    if status == '0' or status == '1' or status == '2' or status == '3':
        feedbacks = mydb.select_feedbacks_by_status(int(status))
    else:
        feedbacks = mydb.selectAllFeedbacks()
    mydb.close()
    return render_template("feedback_list.html",feedbacks=feedbacks)


@app.route('/feedback_item/<id>')
@need_login
def feedback_item(id):
    mydb = DBManager()
    fb = mydb.selectFeedBackById(id)
    mydb.close()
    if fb is None:
        return render_template("msg.html",msg="选择的反馈不存在")
    return render_template("feedback_item.html",fb=fb)


@app.route('/start_process_item/<id>', methods=['POST', 'GET'])
@need_login
def start_process_item(id):
    mydb = DBManager()
    operator_id = session['currentUser']
    mydb.process_one_item_by_id(id, operator_id)
    mydb.close()
    url = "http://%s/feedback_item/%s" %(myconfigReader.domain, id)
    return redirect(url)
    # return feedback_item(id)


@app.route('/end_process_item/<id>', methods=['POST', 'GET'])
@need_login
def end_process_item(id):
    mydb = DBManager()
    operator_id = session['currentUser']
    mydb.end_one_item_by_id(id, operator_id)
    mydb.close()
    url = "http://%s/feedback_item/%s" % (myconfigReader.domain, id)
    return redirect(url)


@app.route('/delete_item/<id>', methods=['POST', 'GET'])
@need_login
@is_admin
def delete_item(id):
    mydb = DBManager()
    operator_id = session['currentUser']
    mydb.delete_one_item_by_id(id, operator_id)
    mydb.close()
    return feedback_list()


@app.route('/revive_item/<id>', methods=['POST', 'GET'])
@need_login
@is_admin
def revive_item(id):
    mydb = DBManager()
    operator_id = session['currentUser']
    mydb.revive_one_item_by_id(id, operator_id)
    mydb.close()
    return feedback_list()


def check_mssql_PGD():
    wx_ms = WX_MSSQL_Push()
    while True:
        wx_ms.push_shouhou_to_wx()
        wx_ms.push_anzhuang_to_wx()
        wx_ms.push_jindu_to_wx()
        wx_ms.push_YXKH_to_wx()
        time.sleep(3)

if __name__ == '__main__':
    #初始化Logger模块
    logging.config.fileConfig(app.root_path + '/log.conf')

    # 检测微信推送的线程，从MSSQL获取数据
    t = threading.Thread(target=check_mssql_PGD, name='checkMSSQL')
    t.start()

    # app.debug = True
    app.secret_key = 'xingtanzjrrjznatgnix2'
    app.permanent_session_lifetime = timedelta(minutes=120)
    app.run(host='0.0.0.0')
